package com.alvis.media.base;

import com.alvis.media.viewmodel.admin.analysis.ModelEvaluationVM;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class PythonVisualize {
    /**
     *  项目中调用Python代码并返回模型评估结果
     */
    public static List<ModelEvaluationVM> invokePythonVisualize()
    {
        BufferedReader reader = null;
        InputStream inputStream = null;

        try
        {
            // 1. 加载配置文件
            Properties properties = new Properties();
            // 配置文件放在resources目录下，使用类加载器读取
            inputStream = PythonVisualize.class.getClassLoader().getResourceAsStream("python-config.properties");
            if (inputStream == null)
            {
                throw new FileNotFoundException("配置文件 python-config.properties 未找到");
            }
            properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 2. 从配置文件获取路径
            String pythonInterpreter = properties.getProperty("python.interpreter.path");
            String pythonScript = properties.getProperty("python.script.path");
            String outputDir = properties.getProperty("python.output.dir");

            // 3. 确保输出目录存在
            File outputDirFile = new File(outputDir);
            if (!outputDirFile.exists()) {
                outputDirFile.mkdirs();
            }

            // 4. 定义命令数组
            String[] cmd = {pythonInterpreter, pythonScript};

            // 5. 启动进程执行命令
            Process process = new ProcessBuilder(cmd)
                    .redirectErrorStream(true)  // 合并错误流到输入流
                    .start();

            // 6. 读取Python的输出
            reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8")
            );

            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                System.out.println("Python输出：" + line);
                output.append(line).append("\n");
            }

            // 7. 等待脚本执行完成
            int exitCode = process.waitFor();
            System.out.println("脚本执行结束，退出码：" + exitCode);

            // 8. 读取生成的JSON结果文件
            if (exitCode == 0) {
                File resultFile = new File(outputDir, "model_evaluation_results.json");
                if (resultFile.exists()) {
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<ModelEvaluationVM> results = objectMapper.readValue(
                        resultFile,
                        new TypeReference<List<ModelEvaluationVM>>() {}
                    );
                    System.out.println("成功读取模型评估结果，共 " + results.size() + " 个模型");
                    return results;
                } else {
                    System.err.println("结果文件不存在: " + resultFile.getAbsolutePath());
                    return new ArrayList<>();
                }
            } else {
                System.err.println("Python脚本执行失败，退出码: " + exitCode);
                return new ArrayList<>();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }finally
        {
            closeAll(inputStream, reader);
        }
    }
    /**
     *  关闭所有的流资源
     */
    public static void closeAll(InputStream inputStream, BufferedReader reader)
    {
        // 关闭资源
        if (reader != null)
        {
            try
            {
                reader.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }

            try
            {
                inputStream.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
